<template>
  <div class="masks">
    <div class="gesturePwd">
      <div class="box">
        <div ref="gestureTitle" class="gestureTitle">{{ state == 1 ? '请绘制您的图形密码' : '请解锁' }}</div>
        <div v-show="state == 1 && firstPwd !== ''" class="setting" ref="updatePassword" @click="updatePassword()">重置密码
        </div>
        <div v-show="state == 2" class="setting" ref="updatePassword" @click="closePwd({
          result: '3',
          pwd: pwd
        })">关闭</div>
        <canvas id="canvas"></canvas>
      </div>
    </div>
  </div>
</template>
    
<script>

export default {
  props: {
    state: {
      type: Number,
      default: 1  // 1-设置密码  2-校验密码
    },
    pwd: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentValue: false,
      ctx: '',
      width: 0,
      height: 0,
      devicePixelRatio: 0,
      chooseType: '',
      r: '',// 公式计算
      lastPoint: [],
      arr: [],
      restPoint: [],
      canvas: '',
      firstIsOver: false,
      firstPwd: ''
    }
  },
  watch: {
    // value: {
    //   handler: function (val) {
    //     this.currentValue = val
    //   },
    //   immediate: true
    // },
    // currentValue(val) {
    //   this.$emit(val ? 'on-show' : 'on-hide')
    //   this.$emit('input', val)
    // }
  },
  created() {
    // if (typeof this.value !== 'undefined') {
    //   this.currentValue = this.value
    // }
  },
  mounted() {
    this.setChooseType(3);
  },
  methods: {
    closePwd(bol) {  // 1-设置成功  2-解锁成功 3-关闭
      console.log(bol)
      this.$emit("handPwd", bol);
      // this.currentValue = false;
    },
    drawCle(x, y) { // 初始化解锁密码面板 小圆圈
      this.ctx.strokeStyle = '#ff9900';//密码的点点默认的颜色
      this.ctx.lineWidth = 2;
      this.ctx.beginPath();
      this.ctx.arc(x, y, this.r, 0, Math.PI * 2, true);
      this.ctx.closePath();
      this.ctx.stroke();
    },
    drawPoint(style) { // 初始化圆心
      for (var i = 0; i < this.lastPoint.length; i++) {
        this.ctx.fillStyle = style;
        this.ctx.beginPath();
        this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2.5, 0, Math.PI * 2, true);
        this.ctx.closePath();
        this.ctx.fill();
      }
    },
    drawStatusPoint(type) { // 初始化状态线条
      for (var i = 0; i < this.lastPoint.length; i++) {
        this.ctx.strokeStyle = type;
        this.ctx.beginPath();
        this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r, 0, Math.PI * 2, true);
        this.ctx.closePath();
        this.ctx.stroke();
      }
    },
    drawLine(style, po, lastPoint) {//style:颜色 解锁轨迹
      this.ctx.beginPath();
      this.ctx.strokeStyle = style;
      this.ctx.lineWidth = 3;
      this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);

      for (var i = 1; i < this.lastPoint.length; i++) {
        this.ctx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
      }
      this.ctx.lineTo(po.x, po.y);
      this.ctx.stroke();
      this.ctx.closePath();

    },
    createCircle() {// 创建解锁点的坐标，根据canvas的大小来平均分配半径
      var n = this.chooseType;
      var count = 0;
			// console.log(this.ctx.canvas.width,'eidrh');
			this.r = this.ctx.canvas.width / (2 +4 * n)
      // this.r = 320 / (2 +4 * n);// 公式计算
			// console.log(this.r,'411');
      this.lastPoint = [];
      this.arr = [];
      this.restPoint = [];
      var r = this.r;
      for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {
          count++;
          var obj = {
            x: j * 4 * r + 3 * r,
            y: i * 4 * r + 3 * r,
            index: count
          };
          this.arr.push(obj);
					// console.log(this.arr,'arr');
          this.restPoint.push(obj);
					// console.log(this.restPoint,'restPoint');
        }
      }
      this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
      for (var i = 0; i < this.arr.length; i++) {
        this.drawCle(this.arr[i].x, this.arr[i].y);

      }
    },
    getPosition(e) {// 获取touch点相对于canvas的坐标
      var rect = e.currentTarget.getBoundingClientRect();
      var po = {
        x: (e.touches[0].clientX - rect.left) * this.devicePixelRatio,
        y: (e.touches[0].clientY - rect.top) * this.devicePixelRatio
      };
      return po;
    },
    update(po) {// 核心变换方法在touchmove时候调用
      this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
      for (var i = 0; i < this.arr.length; i++) { // 每帧先把面板画出来
        this.drawCle(this.arr[i].x, this.arr[i].y);
      }
      this.drawPoint('#27AED5');// 每帧花轨迹
      this.drawStatusPoint('#27AED5');// 每帧花轨迹
      this.drawLine('#27AED5', po, this.lastPoint);// 每帧画圆心
      for (var i = 0; i < this.restPoint.length; i++) {
        if (Math.abs(po.x - this.restPoint[i].x) < this.r && Math.abs(po.y - this.restPoint[i].y) < this.r) {
          this.drawPoint(this.restPoint[i].x, this.restPoint[i].y);
          this.lastPoint.push(this.restPoint[i]);
          this.restPoint.splice(i, 1);
          break;
        }
      }
    },
    getpwdstr(pwd) {
      console.log("1", pwd);
      var p1 = '';
      for (var i = 0; i < pwd.length; i++) {
        p1 += pwd[i].index;
      }
      return p1;
    },
    checkPass(pwd1, pwd2) {// 检测密码
		console.log(pwd1, pwd2);
      return pwd1 === pwd2;
    },
    storePass(pwd2) {// touchend结束之后对密码和状态的处理
      const pwd = this.getpwdstr(pwd2);

      if (pwd.length < 4) {
        this.drawStatusPoint('red');
        this.drawPoint('red');
        this.drawLine('red', this.lastPoint[this.lastPoint.length - 1], this.lastPoint);// 每帧画圆心
        var gestureTitle = this.$refs.gestureTitle;
        gestureTitle.innerHTML = '请连接4个点';

      } else {
        if (this.state == 1 && this.firstIsOver) {
          if (this.checkPass(this.firstPwd, pwd)) {
            this.$refs.gestureTitle.innerHTML = '密码保存成功';
            this.drawStatusPoint('# 42b983');
            // this.drawPoint('# 42b983');
            this.closePwd({
              result: '1',
              pwd: pwd
            });
          } else {
            this.$refs.gestureTitle.innerHTML = '两次不一致，重新输入';
            this.drawStatusPoint('red');
            this.drawPoint('red');
          }
        } else if (this.state == 2) {
          if (this.checkPass(localStorage.getItem("pwd"), pwd)) {
            var gestureTitle = this.$refs.gestureTitle;
            gestureTitle.style.color = "# 42b983";
            gestureTitle.innerHTML = '解锁成功';
            this.drawStatusPoint('# 42b983');//小点点外圈高亮
            this.drawPoint('# 42b983');
            this.drawLine('# 42b983', this.lastPoint[this.lastPoint.length - 1], this.lastPoint);// 每帧画圆心
            this.closePwd({
              result: '2',
              pwd: pwd
            });
          }else {
            this.drawStatusPoint('red');
            this.drawPoint('red');
            this.drawLine('red', this.lastPoint[this.lastPoint.length - 1], this.lastPoint);// 每帧画圆心
            var gestureTitle = this.$refs.gestureTitle;
            gestureTitle.style.color = "red";
            gestureTitle.innerHTML = '密码错误';
          }
        } else {
          this.firstIsOver = true;
          this.firstPwd = pwd;
          this.$refs.gestureTitle.innerHTML = '再次输入';
        }
      }
    },
    makeState() {
      // if (this.state == 2) {
      //   this.$refs.updatePassword.style.display = 'block';
      //   var gestureTitle = this.$refs.gestureTitle;
      //   gestureTitle.style.color = "#87888a";
      //   gestureTitle.innerHTML = '请解锁';
      // } else if (this.state == 1) {
      //   this.$refs.updatePassword.style.display = 'none';
      // } else {
      //   // this.$refs.updatePassword.style.display = 'block';
      // }
    },
    setChooseType(type) {
      this.chooseType = type;
      this.init();
    },
    updatePassword() {

      this.firstIsOver = false;
      this.firstPwd = '';
      this.$refs.gestureTitle.innerHTML = '绘制解锁图案';
      this.reset();
    },
    initDom() {
      this.chooseType = Number(window.localStorage.getItem('chooseType')) || 3;
      this.devicePixelRatio = window.devicePixelRatio || 1;
      var canvas = document.getElementById('canvas');
      var width = this.width || 320;
      var height = this.height || 320;
      // 高清屏锁放
      canvas.style.width = width + "rpx";
      canvas.style.height = height + "rpx";
      canvas.height = height * this.devicePixelRatio;
      canvas.width = width * this.devicePixelRatio;
			console.log(canvas);
    },
    init() {
      this.initDom();
      this.lastPoint = [];
      this.makeState();
      this.touchFlag = false;
      this.canvas = document.getElementById('canvas').childNodes[0];
      console.log(this.canvas,'this.canvas');
      this.ctx = this.canvas.getContext('2d');
      this.$nextTick(() =>{
				this.createCircle();
				this.bindEvent();
			})
    },
    reset() {
      // this.makeState();
      this.createCircle();
    },
    bindEvent() {
      var self = this;
      this.canvas = document.getElementById('canvas');
			console.log(this.canvas);
      this.canvas.addEventListener("touchstart", function (e) {
        e.preventDefault();// 某些android 的 touchmove不宜触发 所以增加此行代码
        var po = self.getPosition(e);
        for (var i = 0; i < self.arr.length; i++) {
          if (Math.abs(po.x - self.arr[i].x) < self.r && Math.abs(po.y - self.arr[i].y) < self.r) {
            self.touchFlag = true;
            self.drawPoint(self.arr[i].x, self.arr[i].y);
            self.lastPoint.push(self.arr[i]);
            self.restPoint.splice(i, 1);
						console.log(self.drawPoint,'drawPoint');
						console.log(self.lastPoint,'lastPoint');
						console.log(self.restPoint,'restPoint');
            break;
          }
        }
      }, false);
      this.canvas.addEventListener("touchmove", function (e) {
        if (self.touchFlag) {
          self.update(self.getPosition(e));
        }
      }, false);
      this.canvas.addEventListener("touchend", function (e) {
        if (self.touchFlag) {
          self.touchFlag = false;
          self.storePass(self.lastPoint);
          setTimeout(function () {
            self.reset();
          }, 1000);
        }
      }, false);
    }
  }
}
</script>
    
<style scoped>
.masks {
  text-align: center;
  /* position: fixed;
  z-index: 1000;
  top: 50px;
  right: 0;
  left: 0;
  bottom: 0; */
  width: 100%;
  background: #f0f0f0;
}

.gesturePwd {

  width: 100%;
  height: 100%;
  text-align: center;
  border-radius: 3px;
  overflow: hidden;
  background-color: #f0f0f0;
  position: relative;
}

.gestureTitle {
  color: #87888a;
  font-size: 20px;
  font-weight: normal;
  margin-top: 10px;
}

.box {
  position: absolute;
  top: 0px;
  left: 0;
  right: 0;
  bottom: 0;
}

.box .setting {
  margin-top: 15px;
  font-size: 21px;
  font-weight: 600;
  color: #ff9900;
}

.box canvas {
  background-color: #f0f0f0;
  display: inline-block;
  width: 320px;
  height: 320px;
}
</style>